package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"monthly/echa"
	"monthly/models"
	"os"
	"path/filepath"
	"time"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Upload() {
	file, m, err := c.GetFile("img")
	if err != nil {
		return
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".jpeg" && ext != ".png" {
		res := Msg{
			Code: 0,
			Msg:  "只能是.png.jpeg.jpg",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if m.Size > 2*1024*1024 {
		res := Msg{
			Code: 0,
			Msg:  "不能超过2MB",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	openFile, err := os.OpenFile("static/img/"+m.Filename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777)
	if err != nil {
		return
	}
	io.Copy(openFile, file)
	res := Msg{
		Code: 200,
		Msg:  "图片上传成功",
		Data: "http://127.0.0.1:8080/static/img/" + m.Filename,
	}
	c.Data["json"] = res
	c.ServeJSON()
}
func (c *NewsController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	state := c.GetString("state")
	ss := models.News{
		Name:  name,
		Img:   img,
		State: state,
	}
	err := models.DB.Debug().Create(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *NewsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	i := (page - 1) * size
	var alloct models.News
	err := models.DB.Debug().Offset(i).Limit(size).Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "查询成功",
			Data: alloct,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}

}
func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	var news models.News
	err := models.DB.Debug().Delete(&models.News{}, id).Error
	news.ID = uint(id)
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		key := fmt.Sprintf("news_del_%v", news.ID)
		jsonData, _ := json.Marshal(news)
		echa.Rdb.Set(echa.Ctx, key, jsonData, time.Second*10)
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
